<script setup>
import { useFloating, autoUpdate, offset, flip, shift, autoPlacement } from "@floating-ui/vue";
import menu from './_menu';
import _ from "lodash";
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import { el } from "element-plus/es/locales.mjs";
import './dropdown.scss'; // 引入公共样式

const root = ref(null);
const current = ref(null);
const floating = ref(null);
const open = ref(false);

const { floatingStyles, update } = useFloating(current, floating, {
    placement: 'bottom-start', // 默认位置
    middleware: [
        offset(0), // 浮层和目标元素之间的间距
        flip({
            fallbackPlacements: ["right-center", "left-center"], // 自动翻转的备选位置
            padding: 10, // 浮层和视口边界之间的最小间距
        }),
        shift({
            padding: 10, // 浮层和视口边界之间的最小间距
        }),
        autoPlacement({
            padding: 10, // 浮层和视口边界之间的最小间距
            allowedPlacements: ['right-center', "left-center", 'bottom-start'], // 允许的位置
        }),
    ],
    whileElementsMounted: autoUpdate, // 自动更新浮层位置
});


menu.bindingHideMenu(root, open);

const switchOpenFn = () => {
    menu.switchOpen(root.value, open);
    update(); 
};
const setCurrent = (el) => {
    current.value = el;
};
</script>

<template>
    <span class="d-inline-block" ref="root" @click="switchOpenFn">
        <slot name="refrence" :ref="setCurrent"></slot>
        <span ref="floating" :style="floatingStyles" v-if="open" class="x-dropdown shadow-lg rounded-3">
            <span class="x-dropdown-item-body">
                <slot name="content"></slot>
            </span>
        </span>
    </span>
</template>